import React, { useState, useEffect } from 'react';
import { List, ImagePicker, Toast, InputItem, Button } from 'antd-mobile';
import { inject, observer } from 'mobx-react';

function Edit(props: any) {
  const { userStore } = props;
  const [files, setFiles] = useState([{ url: userStore.avatar }]);
  const [phone, setPhone] = useState('');
  const [sign, setSign] = useState('');
  const handleChange = (files: any) => {
    if (files[0]?.file?.size / 1024 / 1024 > 0.5) {
      Toast.fail('图片大小不能大于0.5M');
      return;
    }
    setFiles(files);
  };

  const handleSubmit = () => {
    if (!files.length) {
      Toast.fail('请上传图片');
      return;
    } else if (!phone) {
      Toast.fail('请输入电话号码');
    } else if (!sign) {
      Toast.fail('请输入签名');
    } else {
      userStore.editUserAsync({
        avatar: files[0].url,
        phone: phone,
        sign: sign,
      });
    }
  };

  useEffect(() => {
    userStore.getUserAsync({});
  }, []);

  return (
    <div className="user-edit">
      <List>
        <ImagePicker
          files={files}
          selectable={files.length < 1}
          onChange={handleChange}
        />
        <InputItem
          type="phone"
          placeholder="电话"
          value={phone}
          onChange={v => setPhone(v)}
        >
          电话：
        </InputItem>
        <InputItem placeholder="签名" value={sign} onChange={v => setSign(v)}>
          签名：
        </InputItem>
      </List>
      <Button
        type="warning"
        style={{ marginTop: '20px' }}
        onClick={handleSubmit}
      >
        修改
      </Button>
    </div>
  );
}

export default inject('userStore')(observer(Edit));
